'use strict';

const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;
const $ = dbcmd.aggregate;

module.exports = class ShoppingController extends Controller {
	// 查询购物圈
	async userGet() {
		let response = {
			code: 1,
			datas: null,
			msg: ''
		};

		const start = Date.now();
		const {
			// 总数
			isCount,
			// 分页
			page = 1,
			rows = 10,
			orderby = 'create_time desc',
			// 条件
			member_nickname,
			begin_time,
			end_time,
		} = this.ctx.data;

		// 查询条件
		const whereObj = {};

		if (member_nickname) {
			whereObj.member_nickname = new RegExp(this.filterRegexpKey(member_nickname), 'i');
		}

		if (begin_time && end_time) {
			whereObj.create_time = dbcmd.gte(begin_time).and(dbcmd.lte(end_time));
		}

		if (isCount) {
			// 查询总数量
			const countRes = await this.db.collection('usemall-member').where(whereObj).field({
				_id: true
			}).count();
			response.total = countRes.total;
		}

		// 排序规则
		const [field, sort] = orderby.split(' ');
		const userRes = await this.db.collection('usemall-member')
			.where(whereObj)
			.orderBy(field, sort)
			.skip((page - 1) * rows)
			.limit(rows)
			.field({
				member_nickname: true,
				member_headimg: true
			})
			.get();

		const datas = [];
		const ids = userRes.data.map(x => x._id);
		if (ids.length) {
			const shoppingUserRes = await this.db.collection('usemall-shopping-user')
				.where({
					_id: dbcmd.in(ids)
				})
				.limit(ids.length)
				.get();

			shoppingUserRes.data.forEach(x => {
				const member = userRes.data.find(m => m._id === x._id);
				datas.push({
					...x,
					member
				})
			});
		}
		response.datas = datas;

		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}

	// 详情数据
	async detail() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		};

		const start = Date.now();
		const {
			id
		} = this.ctx.data;

		if (!id) {
			this.throw('查询笔记人不存在');
		}

		// 查询笔记人
		const shoppingUserRes = await this.db.collection('usemall-shopping-user')
			.doc(id)
			.field({
				notep_note: true,
				notep_attention: true,
				notep_fans: true,
				notep_praise: true,
				notep_collect: true,
				notep_likes: true,
				notep_by_collect: true,
				create_time: true,
				create_uid: true
			})
			.get();
		const [shoppingUser] = shoppingUserRes.data;

		// 查询笔记人用户
		const memberRes = await this.db.collection('usemall-member')
			.doc(shoppingUser.create_uid)
			.field({
				member_headimg: true,
				member_nickname: true,
				member_gender: true,
				member_city: true
			})
			.get();
		const [member] = memberRes.data;

		response.datas.detail = {
			...shoppingUser,
			...member
		}

		// 查询汇总数据
		const totalRes = await this.total();
		response.datas.total = totalRes.datas;

		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}

	// 汇总数据
	async total() {
		let response = {
			code: 1,
			datas: null,
			msg: ''
		};

		const start = Date.now();
		const {
			id
		} = this.ctx.data;

		// 查询数据数
		const orderRes = await this.db.collection('usemall-shopping-note').where({
			create_uid: id
		}).field({
			_id: true
		}).count();

		response.datas = {
			note_cnt: orderRes.total
		};

		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.duration = `耗时：${end - start}ms`;
		return response;
	}

	// 过滤特殊字符
	filterRegexpKey(str) {
		if (!str) return '';

		str += '';

		const arr = ['\\', '$', '(', ')', '*', '+', '.', '[', ']', '?', '^', '{', '}', '|'];

		arr.forEach(x => {
			str = str.replace(new RegExp(`\\${x}`), `\\${x}`);
		});

		return str;
	}
}